package com.michael.retail.auth.granter;

import com.michael.retail.auth.service.ValidCodeService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 类功能描述:
 * <pre>
 *   账号+密码+验证码授权模式
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/12 17:20
 */
public class PasswordValidCodeGranter extends ResourceOwnerPasswordTokenGranter {

    private static final String GRANT_TYPE = "password_code";

    private final ValidCodeService validCodeService;

    public PasswordValidCodeGranter(
            AuthenticationManager authenticationManager,
            AuthorizationServerTokenServices tokenServices,
            ClientDetailsService clientDetailsService,
            OAuth2RequestFactory requestFactory,
            ValidCodeService validCodeService
    ) {
        super(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.validCodeService = validCodeService;
    }

    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        // 请求编号(唯一)
        String requestId = parameters.get("requestId");
        String validCode = parameters.get("validCode");
        //校验图形验证码
        validCodeService.validate(requestId, validCode);

        return super.getOAuth2Authentication(client, tokenRequest);
    }
}
